#!/usr/bin/env python3
"""
RedFire 配置生成工具
根据模板生成环境变量配置文件
"""

import os
import secrets
import string
from pathlib import Path
from typing import Dict, Any


class ConfigGenerator:
    """配置生成器"""
    
    def __init__(self):
        self.project_root = Path(__file__).parent.parent
    
    def generate_password(self, length: int = 16) -> str:
        """生成安全密码"""
        characters = string.ascii_letters + string.digits + "!@#$%^&*"
        return ''.join(secrets.choice(characters) for _ in range(length))
    
    def generate_jwt_secret(self, length: int = 32) -> str:
        """生成JWT密钥"""
        return secrets.token_urlsafe(length)
    
    def generate_config_template(self) -> Dict[str, Any]:
        """生成配置模板"""
        return {
            # 基础环境配置
            'REDFIRE_ENVIRONMENT': 'development',
            'REDFIRE_DEBUG': 'true',
            'REDFIRE_LOG_LEVEL': 'INFO',
            
            # PostgreSQL 配置
            'REDFIRE_POSTGRES_HOST': 'postgresql-primary',
            'REDFIRE_POSTGRES_PORT': '5432',
            'REDFIRE_POSTGRES_DB': 'redfire_stage2',
            'REDFIRE_POSTGRES_USER': 'redfire_prod',
            'REDFIRE_POSTGRES_PASSWORD': self.generate_password(24),
            
            # MySQL 配置
            'REDFIRE_MYSQL_HOST': 'localhost',
            'REDFIRE_MYSQL_PORT': '3307',
            'REDFIRE_MYSQL_DB': 'redfire_trading_test',
            'REDFIRE_MYSQL_USER': 'redfire_app',
            'REDFIRE_MYSQL_PASSWORD': 'redfire_app_2025',
            
            # Redis 配置
            'REDFIRE_REDIS_HOST': 'localhost',
            'REDFIRE_REDIS_PORT': '6379',
            'REDFIRE_REDIS_DB': '1',
            'REDFIRE_REDIS_PASSWORD': 'redfire_redis_2025',
            
            # JWT 配置
            'REDFIRE_JWT_SECRET': self.generate_jwt_secret(32),
            'REDFIRE_JWT_ALGORITHM': 'HS256',
            'REDFIRE_JWT_EXPIRE_HOURS': '24',
            
            # 服务端口配置
            'REDFIRE_API_GATEWAY_PORT': '8000',
            'REDFIRE_USER_SERVICE_PORT': '8001',
            'REDFIRE_TRADING_SERVICE_PORT': '8002',
            'REDFIRE_MARKET_DATA_PORT': '8003',
            'REDFIRE_NOTIFICATION_PORT': '8004',
            'REDFIRE_MONITORING_PORT': '8005',
            
            # 外部服务配置
            'REDFIRE_TUSHARE_TOKEN': 'your_tushare_token_here_23chars',
            
            # API配置
            'REDFIRE_API_PREFIX': '/api/v1',
            'REDFIRE_CORS_ORIGINS': '["http://localhost:3000", "http://localhost:8080"]'
        }
    
    def write_env_file(self, config: Dict[str, Any], filename: str = ".env.generated") -> str:
        """写入环境变量文件"""
        env_file_path = self.project_root / filename
        
        with open(env_file_path, 'w', encoding='utf-8') as f:
            f.write("# RedFire 环境变量配置文件\n")
            f.write(f"# 生成时间: {self._get_current_time()}\n")
            f.write("# 请根据实际环境修改以下配置\n\n")
            
            # 按组织写入配置
            sections = {
                'ENVIRONMENT': ['REDFIRE_ENVIRONMENT', 'REDFIRE_DEBUG', 'REDFIRE_LOG_LEVEL'],
                'POSTGRES': ['REDFIRE_POSTGRES_HOST', 'REDFIRE_POSTGRES_PORT', 'REDFIRE_POSTGRES_DB', 
                           'REDFIRE_POSTGRES_USER', 'REDFIRE_POSTGRES_PASSWORD'],
                'MYSQL': ['REDFIRE_MYSQL_HOST', 'REDFIRE_MYSQL_PORT', 'REDFIRE_MYSQL_DB',
                         'REDFIRE_MYSQL_USER', 'REDFIRE_MYSQL_PASSWORD'],
                'REDIS': ['REDFIRE_REDIS_HOST', 'REDFIRE_REDIS_PORT', 'REDFIRE_REDIS_DB', 'REDFIRE_REDIS_PASSWORD'],
                'JWT': ['REDFIRE_JWT_SECRET', 'REDFIRE_JWT_ALGORITHM', 'REDFIRE_JWT_EXPIRE_HOURS'],
                'SERVICES': ['REDFIRE_API_GATEWAY_PORT', 'REDFIRE_USER_SERVICE_PORT', 'REDFIRE_TRADING_SERVICE_PORT',
                           'REDFIRE_MARKET_DATA_PORT', 'REDFIRE_NOTIFICATION_PORT', 'REDFIRE_MONITORING_PORT'],
                'EXTERNAL': ['REDFIRE_TUSHARE_TOKEN'],
                'API': ['REDFIRE_API_PREFIX', 'REDFIRE_CORS_ORIGINS']
            }
            
            for section_name, keys in sections.items():
                f.write(f"# {section_name} 配置\n")
                for key in keys:
                    if key in config:
                        value = config[key]
                        # 如果值包含特殊字符，用引号包围
                        if any(char in str(value) for char in [' ', '[', ']', '"', "'"]):
                            f.write(f'{key}="{value}"\n')
                        else:
                            f.write(f'{key}={value}\n')
                f.write('\n')
        
        return str(env_file_path)
    
    def _get_current_time(self) -> str:
        """获取当前时间字符串"""
        from datetime import datetime
        return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    def generate_docker_compose_env(self) -> str:
        """生成Docker Compose环境变量文件"""
        config = self.generate_config_template()
        return self.write_env_file(config, ".env.docker")
    
    def generate_standard_env(self) -> str:
        """生成标准环境变量文件"""
        config = self.generate_config_template()
        return self.write_env_file(config, ".env.generated")


def main():
    """主函数"""
    print("RedFire 配置生成工具")
    print("=" * 40)
    
    generator = ConfigGenerator()
    
    try:
        # 生成标准环境配置
        env_file = generator.generate_standard_env()
        print(f"✅ 已生成标准环境配置文件: {env_file}")
        
        # 生成Docker环境配置
        docker_env_file = generator.generate_docker_compose_env()
        print(f"✅ 已生成Docker环境配置文件: {docker_env_file}")
        
        print("\n📝 注意事项:")
        print("1. 请根据实际环境修改生成的配置文件")
        print("2. 生产环境请务必修改默认密码和密钥")
        print("3. 确保敏感配置不要提交到版本控制系统")
        print("4. 使用前请运行配置验证工具检查配置正确性")
        
    except Exception as e:
        print(f"❌ 生成配置文件失败: {e}")
        return 1
    
    return 0


if __name__ == "__main__":
    exit(main())
